package com.theta.common.base.swagger.doc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;
import com.github.xiaoymin.knife4j.aggre.core.RouteCache;
import com.github.xiaoymin.knife4j.aggre.core.RouteDispatcher;
import com.github.xiaoymin.knife4j.aggre.core.RouteRepository;
import com.github.xiaoymin.knife4j.aggre.core.common.ExecutorEnum;
import com.github.xiaoymin.knife4j.aggre.core.pojo.SwaggerRoute;
import com.github.xiaoymin.knife4j.aggre.repository.NacosRepository;
import com.github.xiaoymin.knife4j.aggre.spring.configuration.Knife4jAggregationAutoConfiguration;
import com.github.xiaoymin.knife4j.aggre.spring.configuration.Knife4jAggregationProperties;
import com.theta.common.base.swagger.doc.core.ThetaRouteDispatcher;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Configuration
@EnableConfigurationProperties({Knife4jAggregationProperties.class})
@ConditionalOnProperty(name = "knife4j.enableAggregation",havingValue = "true")
public class Knife4jAggregationExtAutoConfiguration extends Knife4jAggregationAutoConfiguration	{
	
	
	@Value("${knife4j.nacos.serviceUrl:}")
    private String serviceUrl;
	
	
	@Bean
	@LoadBalanced
	public RestTemplate restTemplate( ) {
		return new RestTemplate();
	}
	
	public Knife4jAggregationExtAutoConfiguration(Environment environment) {
		super(environment);
	}
	
	@Bean
    @Order(1)
    @Primary
    @ConditionalOnProperty(name = "knife4j.nacos.enable",havingValue = "true")
    public NacosRepository nacosRepository(@Autowired Knife4jAggregationProperties knife4jAggregationProperties){
    	log.info("nacosRepository {}",this.serviceUrl);
    	NacosExtendRepository repo= new NacosExtendRepository(knife4jAggregationProperties.getNacos());
    	return repo;
    }

	@Bean
	public RouteDispatcher routeDispatcher(RouteRepository routeRepository,
			RouteCache<String, SwaggerRoute> routeCache,RestTemplate restTemplate) {
		log.info("Knife4jAggregationExtAutoConfiguration  -->{}");
		ThetaRouteDispatcher dispatcher=new ThetaRouteDispatcher(routeRepository,routeCache, ExecutorEnum.APACHE,"/");
		return dispatcher;
	}
	
	
	

}
